package ru.batrdmi.svnplugin;

import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.actions.VcsContextFactory;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.idea.svn.SvnStatusUtil;
import org.jetbrains.idea.svn.SvnVcs;
import org.tmatesoft.svn.core.SVNException;

public class SVNRevisionGraphAction extends AnAction {
    private static final String ERROR_DIALOG_TITLE = "Revision Graph Error";

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getData(DataKeys.PROJECT);
        if (project == null) {
            Messages.showErrorDialog("Cannot access project", ERROR_DIALOG_TITLE);
            return;
        }
        VirtualFile file = e.getData(DataKeys.VIRTUAL_FILE);
        if (file == null) {
            Messages.showErrorDialog(project, "Cannot access file", ERROR_DIALOG_TITLE);
            return;
        }
        ProjectLevelVcsManager vcsManager = ProjectLevelVcsManager.getInstance(project);
        if (vcsManager == null) {
            Messages.showErrorDialog(project, "VCS is not enabled for project " + project.getName(), ERROR_DIALOG_TITLE);
            return;
        }
        AbstractVcs vcs = vcsManager.getVcsFor(file);
        if (!(vcs instanceof SvnVcs)) {
            Messages.showErrorDialog(project, file.getName() + " is not managed by Subversion", ERROR_DIALOG_TITLE);
            return;
        }

        VcsContextFactory vcsContext = VcsContextFactory.SERVICE.getInstance();
        FilePath filePath = vcsContext.createFilePathOn(file);

        SVNRevisionGraph.createAndShow(project, filePath);
    }

    @Override
    public void update(AnActionEvent e) {
        Presentation presentation = e.getPresentation();
        final DataContext dataContext = e.getDataContext();

        Project project = PlatformDataKeys.PROJECT.getData(dataContext);
        if (project == null) {
            presentation.setEnabled(false);
            presentation.setVisible(false);
            return;
        } else {
            presentation.setVisible(true);
        }

        VirtualFile[] files = PlatformDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
        SvnVcs vcs = SvnVcs.getInstance(project);

        presentation.setEnabled(files != null
                && files.length == 1
                && ProjectLevelVcsManager.getInstance(project).checkAllFilesAreUnder(vcs, files)
                && SvnStatusUtil.isUnderControl(project, files[0]));
    }
}
